package com.lamer.console.common.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lamer.console.base.entity.UserDetailsImpl;
import com.lamer.console.common.api.ApiResult;
import com.lamer.console.common.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String tokenPrefix = operations.get("JWT.TOKEN.PREFIX");
        UserDetailsImpl userDetailsImpl = (UserDetailsImpl)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String token = jwtTokenUtil.generateToken(userDetailsImpl.getUsername());
        Map<String, Object> map = new HashMap<>();
        map.put("token", tokenPrefix + " " + token);//token前缀和token间须有空格，#spring security
        map.put("user", userDetailsImpl);

        ApiResult<Map<String, Object>> success = ApiResult.success("登录成功", map);
        httpServletResponse.setContentType("text/json;charset=UTF8");
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(success));
    }

}
